package com.tx.framework.system;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tx.framework.exception.CheckedException;
import com.tx.framework.exception.NoLoginException;

@ControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = CheckedException.class)
	@ResponseBody
	public ResultBody<?> checkedExceptionHandler(HttpServletRequest request,
			CheckedException e) {
		e.printStackTrace();
		return ResultBody.exception(e.getMessage());
	}

	@ExceptionHandler(value = NoLoginException.class)
	@ResponseBody
	public ResultBody<?> noLoginExceptionHandler(HttpServletRequest request,
			NoLoginException e) {
		return ResultBody.noLogin(e.getMessage());
	}

	@ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
	@ResponseBody
	public ResultBody<?> handleException(
			HttpRequestMethodNotSupportedException e) {
		return ResultBody.exception("不支持' " + e.getMethod() + "'请求");
	}

	@ExceptionHandler(RuntimeException.class)
	@ResponseBody
	public ResultBody<?> notFound(RuntimeException e) {
		e.printStackTrace();
		return ResultBody.exception("运行时异常:" + e.getMessage());
	}

	@ExceptionHandler(value = NullPointerException.class)
	@ResponseBody
	public ResultBody<?> exceptionHandler(HttpServletRequest request,
			NullPointerException e) {
		e.printStackTrace();
		return ResultBody.exception("NullPointerException");
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public ResultBody<?> exceptionHandler(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		String errorMesssage = "";
		for (FieldError fieldError : bindingResult.getFieldErrors()) {
			errorMesssage += fieldError.getDefaultMessage() + "!";
		}
		return ResultBody.exception(errorMesssage);
	}

	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public ResultBody<?> exceptionHandler(HttpServletRequest request,
			Exception e) {
		e.printStackTrace();
		return ResultBody.exception(e.getMessage());
	}
}
